<?php

namespace App\Admin\Controllers;

use App;

use Encore\Admin\Form;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form as WForm;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use App\Models\TestingDetail;
use CategoryService;
use TestingDetailService;
use TestingItemService;
use App\Models\LogHelper;
use Illuminate\Support\Facades\Request;
use Excel;

class TestingDetailController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('backend.testing_detail.title.list'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header(trans('backend.testing_detail.title.edit'));
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('backend.testing_detail.title.add'));
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(TestingDetail::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->id('ID')->sortable();
            $grid->icon('icon')->image();
            $grid->name(trans('backend.testing_detail.column.name'));
            $grid->note(trans('backend.testing_detail.column.note'));
            $grid->cate_id(trans('backend.testing_detail.column.cate_id'))->value(function($cate_id){
                return CategoryService::getById($cate_id)->name;
            })->badge('blue');
//            $grid->theme(trans('backend.testing_detail.column.theme'))->value(function($theme){
//                return $this->transTheme($theme);
//            });

            $grid->items(trans('backend.testing_detail.column.questions_count'))->value(function ($items) {
                $count = count($items);
                return "<span class='label label-warning'>{$count}</span>";
            });
//            $grid->questions_count(trans('backend.testing_detail.column.questions_count'));
            $grid->test_times(trans('backend.testing_detail.column.test_times'));
            $grid->created_at(trans('backend.testing_detail.column.created_at'));




            $grid->filter(function ($filter) {
                $filter->useModal();
                $filter->like('name',trans('backend.testing_detail.search.name'));
            });

            $grid->rows(function($row){
                // 添加自定义操作按钮
                $row->actions()->add(function ($row) {
                    return "<a title='上传测评题目' href='/admin/testing/detail/{$row->id}/upload/questions/'><i class='fa fa-cloud-upload'></i></a>";
                });
                $row->actions()->add(function ($row) {
                    return "<a title='查看题目列表' href='/admin/testing/detail/item/{$row->id}'><i class='fa fa-tree'></i></a>";
                });
            });

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(TestingDetail::class, function (Form $form) {
            $form->text('name', trans('backend.testing_detail.column.name'))->rules('required');
            $form->textarea('note', trans('backend.testing_detail.column.note'));
            $form->select('cate_id', trans('backend.testing_detail.column.cate_id'))->options('/admin/cate/options')->rules('required');
            $form->select('theme', trans('backend.testing_detail.column.theme'))->options([1=>'默认主题'])->rules('required');
            $form->image('icon', trans('backend.testing_detail.column.icon'))->rules('mimes:jpg,jpeg,png,bmp');
            $form->multipleSelect('result_type', trans('backend.testing_detail.column.result_type'))->options('/admin/testing/result/type/options');
            $form->number('time', trans('backend.testing_detail.column.time'))->rules('required');
            $form->textarea('gist', trans('backend.testing_detail.column.gist'));
        });
    }


    protected function transTheme($theme){
        $themeName = '默认主题';
        switch ($theme){
            default :
                $themeName = '默认主题';
                break;
        }
        return $themeName;
    }


    public function uploadQuestions($id){
        $testingDetail = TestingDetailService::getById($id);
        return Admin::content(function (Content $content) use($testingDetail) {
            $form = new WForm();
            $form->display('name',trans('backend.testing_detail.title.name'))->value(function() use($testingDetail){
                return $testingDetail->name;
            });
            $form->action('/admin/testing/detail/upload/questions/save');
            $form->hidden('testing_id');
            $form->file('questions_file',trans('backend.testing_detail.column.questions_file'))->rules('mimes:xls,xlsx');
            $content->row(new Box(trans('backend.testing_detail.title.upload_question'), $form));
        });
    }


    public function saveUploadQuestion(){
        return apiSuccess('success');
    }


    /**
     * testing/question/import/tid/2/key/healthtesting
     * testing/question/import/tid/1/key/highblood
     * testing/question/import/tid/3/key/psytesting
     */
    public function importQuetionDataFromExcel($tid,$key){

        $filePath = 'public/upload/testing/excel/'.$key.'.xlsx';
        Excel::load($filePath, function($reader) use($tid) {
            $allData = $reader->all();
            $data = $allData[0];
            $batchData = [];
            $optionTypes = [1,2,7,8];
            $dynamicTypes = [4,6];
            foreach ($data as $d){
                if($d['no']){
                    $obj['index'] = $d['no'];
                    $obj['testing_id'] = $tid;
                    $obj['question_type'] = $d['type'];
                    $obj['title'] = $d['question'];
                    $optionStr = $d['answerweight'];
                    if(in_array($d['type'],$optionTypes)){
                        $obj['options'] = TestingItemService::convertQuestionOptions($optionStr);
                    }else{
                        $obj['options'] = '';
                    }

                    if(in_array($d['type'],$dynamicTypes)){
                        $obj['expression'] = str_replace("\n",'|||',$optionStr);
                    }else{
                        $obj['expression'] = '';
                    }
//                    $obj['middle_var'] = $d['mid_var']?1:0;
                    $obj['blank_type'] = $d['blank_type'];
                    array_push($batchData,$obj);
                }
            }
            TestingItemService::batchInsertData($batchData);
            echo json_encode($batchData);
        });
 }

    public function getOptions(){
        return TestingDetailService::getOptions();
    }
}



